package com.xxx.mch.service.impl;

import com.xxx.mch.dao.GenresTemplateMapper;
import com.xxx.mch.domain.dto.GenresTemplateDto;
import com.xxx.mch.domain.po.GenresTemplate;
import com.xxx.mch.exception.BusinessException;
import com.xxx.mch.service.GenresService;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author FengHaixin
 * @description 一句话描述该文件的用途
 * @date 2020-09-12
 */
@Service
public class GenresServiceImpl implements GenresService
{
    @Resource
    private GenresTemplateMapper genresTemplateMapper;


    @Override
    public List<GenresTemplateDto> getTemplate()
    {
        List<GenresTemplate> genresTemplates = genresTemplateMapper.selectAll();
        return genresTemplates.stream().map(genresTemplate -> {
            GenresTemplateDto dto = new GenresTemplateDto();
            BeanUtils.copyProperties(genresTemplate, dto);
            return dto;
        }).collect(Collectors.toList());
    }


    @Override
    public void updateTemplate(List<GenresTemplateDto> templates)
    {
        if (CollectionUtils.isEmpty(templates))
        {
            return;
        }

        templates.forEach(template -> {
            if (Objects.isNull(template.getId()))
            {
                throw new BusinessException("id不能为空");
            }
            GenresTemplate genresTemplate = new GenresTemplate();
            BeanUtils.copyProperties(template, genresTemplate);
            genresTemplateMapper.updateByPrimaryKeySelective(genresTemplate);
        });
    }


    @Override
    public void createTemplate(List<GenresTemplateDto> templates)
    {
        if (CollectionUtils.isEmpty(templates))
        {
            return;
        }

        templates.forEach(template -> {
            GenresTemplate genresTemplate = new GenresTemplate();
            BeanUtils.copyProperties(template, genresTemplate);
            genresTemplate.setId(null);
            genresTemplateMapper.insertSelective(genresTemplate);
        });
    }


    @Override
    public void deleteTemplate(Integer id)
    {
        genresTemplateMapper.deleteByPrimaryKey(id);
    }


    @Override
    public GenresTemplateDto getTemplate(Integer genresId)
    {
        GenresTemplate genresTemplate = genresTemplateMapper.selectByPrimaryKey(genresId);
        if (Objects.isNull(genresTemplate))
        {
            throw new BusinessException("体裁模板id不存在：" + genresId);
        }
        GenresTemplateDto dto = new GenresTemplateDto();
        BeanUtils.copyProperties(genresTemplate, dto);
        return dto;
    }
}
